package cc.sunwl.study.springboot2.service.impl;

import cc.sunwl.study.springboot2.entity.Article;
import cc.sunwl.study.springboot2.repo.ArticleRepo;
import cc.sunwl.study.springboot2.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * ServerResponse 类似 Spring Web 的 ResponseEntity 用来封装响应数据，包括状态码、HTTP 头等信息。在 ServerResponse 对象中，ServerResponse 包含大量有用的默认方法，如 notFound(), ok(), accepted(),  created() 等等。这些方法可以用来创建不同类型的响应信息。
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    private final ArticleRepo articleRepo;

    @Autowired
    public ArticleServiceImpl(ArticleRepo articleRepo) {
        this.articleRepo = articleRepo;
    }

    @Override
    public Mono<Article> get(String id) {
        return articleRepo.findById(id).onErrorReturn(new Article());
    }

    /*@Override
    public Mono<ServerResponse> get1(String id) {
        return articleRepo.findById(id)
                .flatMap(article -> ServerResponse.ok().body(Mono.just(article), Article.class))
                .switchIfEmpty(ServerResponse.notFound().build());
    }*/

    @Override
    public Mono<Article> add(Article entity) {
        return articleRepo.insert(entity);
    }

    @Override
    public Mono<Article> put(Article entity) {
        Mono<Boolean> booleanMono = articleRepo.existsById(entity.getId());
        if (booleanMono.block()) {
            return articleRepo.save(entity);
        } else {
            return Mono.empty();
        }
    }

    @Override
    public Mono<Void> delete(String id) {
        return articleRepo.deleteById(id);
    }

    @Override
    public Flux<Article> list(int page, int size) {
        return articleRepo.findAll();
    }
}
